#pragma strict

var tank : GameObject;

private var scriptsGObj : GameObject;

private var BZ3UtilsComponent : BZ3Utils;

//Tank values
var tankAmount = 1;
private var speed = 4;
private var mass = 100;
private var drag = 0;
private var spawnPositionTankY = -1;
private var spawnPositionTank : Vector3;
private var spawnRotationTank : Quaternion;

private var outOfRangeDistance : int = 500;
private var randomRangePos : float = 480;
private var randomRangeNeg : float = -480;

private var deadZoneNeg : float = -300;
private var deadZonePos : float = 300;
private var groundGObj : GameObject;

function Start () {
	scriptsGObj = GameObject.FindGameObjectWithTag("Scripts");
	groundGObj = GameObject.FindGameObjectWithTag("Ground");
	
	BZ3UtilsComponent = scriptsGObj.GetComponent(BZ3Utils);
}

function Update () {
	if(GameObject.FindGameObjectsWithTag("Tank").Length < tankAmount){
		CreateTank(scriptsGObj.transform);
	}
	
	for(var tankTmp : GameObject in GameObject.FindGameObjectsWithTag("Tank")){
		var distance : float = Vector3.Distance(tankTmp.transform.position, scriptsGObj.transform.position);
//		Debug.Log("Name: " + tankTmp.name + " InstanceID: " + tankTmp.GetInstanceID + " Distance: " + distance);
		
		if(distance > outOfRangeDistance){
			RepositionTank(tankTmp, scriptsGObj.transform);
		}
	}
}

public function CreateTank(trans : Transform) {
	//Spawnposition in correlation with the playerposition
	var groundBounds = groundGObj.collider.bounds;
	spawnPositionTank = Vector3(Random.Range(groundBounds.min.x,groundBounds.max.x),0,Random.Range(groundBounds.min.z,groundBounds.max.z));
	spawnRotationTank = transform.rotation;
	
	var go : GameObject = Instantiate(tank, spawnPositionTank, spawnRotationTank);
		go.rigidbody.constraints = RigidbodyConstraints.FreezePositionY | RigidbodyConstraints.FreezeRotationX | RigidbodyConstraints.FreezeRotationZ;
	
		var sphere: GameObject = GameObject.CreatePrimitive(PrimitiveType.Cube);
		sphere.transform.localScale += Vector3(12,12,25);
		sphere.transform.position = go.transform.position;
		sphere.transform.rotation = go.transform.rotation;
		sphere.transform.parent = go.transform;
		sphere.transform.position.y = 300;
		sphere.renderer.material.color = Color(2,0,0,1);
		
		go.rigidbody.position = spawnPositionTank;
		go.rigidbody.rotation = spawnRotationTank;
		go.rigidbody.mass = mass;
		go.rigidbody.drag = drag;
		
		go.rigidbody.velocity = transform.TransformDirection(Vector3(0, 0, speed));
}

public function RepositionTank(tank : GameObject, trans : Transform){
	tank.transform.position = Vector3(trans.position.x + BZ3UtilsComponent.deadZoneRandomRange(randomRangeNeg, randomRangePos, deadZoneNeg, deadZonePos), spawnPositionTankY, trans.position.z + BZ3UtilsComponent.deadZoneRandomRange(randomRangeNeg, randomRangePos, deadZoneNeg, deadZonePos));
	tank.transform.rotation = transform.rotation;
}

public function increaseTankAmount(value : int){
	tankAmount += value;
}